package cn.kingshion.juc.locks;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁
 */
public class ReadWriteLockTest {
    public static void main(String[] args) {
        ReadWriteLockDemo readWriteLock = new ReadWriteLockDemo();

        new Thread(() -> {
            readWriteLock.set((int) (Math.random() * 101));
        }, "write").start();

        for (int i = 0; i < 100; i++) {
            new Thread(() -> {
                readWriteLock.get();
            }, "T " + i).start();
        }
    }
}

class ReadWriteLockDemo {
    private int number = 0;

    private ReadWriteLock lock = new ReentrantReadWriteLock();

    /**
     * 读操作
     */
    public void get() {
        lock.readLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + ":" + number);
        } finally {
            lock.readLock().unlock();
        }
    }

    /**
     * 写操作
     *
     * @param number
     */
    public void set(int number) {
        lock.writeLock().lock();
        try {
            System.out.println(Thread.currentThread().getName() + ":写");
            this.number = number;
        } finally {
            lock.writeLock().unlock();
        }
    }

}


